//1、引入http模块
let http = require('http')
let path = require('path')
let url = require('url')
let fs = require('fs')

let mime = require('./js/mime.js')

//2、创建服务
let server = http.createServer(function (request, response) {
	//4、设置跨域
	response.setHeader('Access-Control-Allow-Origin', '*')
	//5、解析request的请求路径
	let requestUrl = request.url
	//6、使用nodejs的url模块和路径path模块对路径进行解析
	let pathName = url.parse(requestUrl).pathname
	console.log(pathName)
	//7、获得请求路径的扩展名
	let extendName = path.extname(pathName)
	//8、根据请求的pathName名称不同返回不同的内容
	if (pathName === '/') {
		//返回index.html
		fs.readFile('./static/index.html', (err, data) => {
			//.html的mime=text/html;charset=UTF8
			response.setHeader('Content-type', 'text/html;charset=UTF8')
			response.end(data)
		})
	} else if (pathName === '/favicon.ico') {
		//返回一个favicon.ico
		fs.readFile('./static/favicon.ico', (err, data) => {
			//.ico的mime=image/x-icon
			response.setHeader('Content-type', 'image/x-icon')
			response.end(data)
		})
	} else if (pathName === '/index.css') {
		//返回一个index.css
		fs.readFile('./static/index.css', (err, data) => {
			//.css的mime=text/css;charset=UTF8
			response.setHeader('Content-type', 'text/css;charset=UTF8')
			response.end(data)
		})
	} else if (pathName === '/logo.png') {
		//返回一个logo.png
		fs.readFile('./static/logo.png', (err, data) => {
			//.png的mime=image/png
			response.setHeader('Content-type', 'image/png')
			response.end(data)
		})
	} else if (pathName === '/404.jpg') {
		//返回一个404.jpg
		fs.readFile('./static/404.jpg', (err, data) => {
			//.jpg的mime=image/jpeg
			response.setHeader('Content-type', 'image/jpeg')
			response.end(data)
		})
	} else if (pathName === '/jquery-3.4.1.js') {
		//返回一个jquery-3.4.1.js
		fs.readFile('./static/jquery-3.4.1.js', (err, data) => {
			//.js的mime=application/x-javascript
			response.setHeader(
				'Content-type',
				'application/x-javascript;charset=UTF8'
			)
			response.end(data)
		})
	} else if (pathName === '/404.css') {
		//返回一个404.css
		fs.readFile('./static/404.css', (err, data) => {
			//.css的mime=text/css;charset=UTF8c
			response.setHeader('Content-type', 'text/css;charset=UTF8')
			response.end(data)
		})
	} else {
		//返回一个404.html
		fs.readFile('./static/404.html', (err, data) => {
			response.setHeader('Content-type', 'text/html;charset=UTF8')
			response.end(data)
		})
	}
})
//3、启动服务
server.listen(8001, '127.0.0.1', () => {
	console.log('服务启动了，监听在http://127.0.0.1:8001地址')
})
